package com.openroom.ui.component;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.ibatis.type.NStringTypeHandler;
import org.apache.log4j.Logger;
import org.apache.pivot.beans.BXMLSerializer;
import org.apache.pivot.beans.Bindable;
import org.apache.pivot.collections.Map;
import org.apache.pivot.serialization.SerializationException;
import org.apache.pivot.util.Resources;
import org.apache.pivot.util.concurrent.Task;
import org.apache.pivot.util.concurrent.TaskExecutionException;
import org.apache.pivot.util.concurrent.TaskListener;
import org.apache.pivot.wtk.Border;
import org.apache.pivot.wtk.BoxPane;
import org.apache.pivot.wtk.Component;
import org.apache.pivot.wtk.ComponentMouseButtonListener;
import org.apache.pivot.wtk.ComponentMouseListener;
import org.apache.pivot.wtk.Container;
import org.apache.pivot.wtk.Cursor;
import org.apache.pivot.wtk.FlowPane;
import org.apache.pivot.wtk.Label;
import org.apache.pivot.wtk.Mouse.Button;
import org.apache.pivot.wtk.media.Picture;

import com.openroom.event.ApplicationEvent;
import com.openroom.event.EventHandler;
import com.openroom.event.EventManager;
import com.openroom.event.EventType;
import com.openroom.model.ModelLocator;
import com.openroom.model.ModelLocator.ModeFlag.SelectMode;
import com.openroom.model.Photograph;
import com.openroom.ui.FocusableImageView;
import com.openroom.ui.MainWindow;

public class ThumbnailPanel extends FlowPane implements Bindable {

    private static final Logger LOGGER = Logger.getLogger(ThumbnailPanel.class);
    public static int imageCounter = 1;

    private static ModelLocator instance = ModelLocator.getInstance();

    public ThumbnailPanel() {
        LOGGER.info("ThumbnailPanel.ThumbnailPanel()");
        EventManager.getInstance().listenToEventType(
                EventType.ALL_IMAGE_CHANGED, new EventHandler() {
                    @Override
                    public void handle(ApplicationEvent event) {
                        imageCounter = 1;
                    }
                });
        EventManager.getInstance().listenToEventType(
                EventType.ALL_SHOWING_IMAGE_CHANGED, new EventHandler() {
                    @Override
                    public void handle(ApplicationEvent event) {
                        imageCounter = 1;
                        long start = System.nanoTime();
                        int length = getLength();
                        List<Photograph> allPhotographsOfFolder = instance
                                .getAllShowingImage();
                        if (length > 0) {
                            for (int i = 0; i < length; i++) {
                                ThumbnailView imageview = (ThumbnailView) get(i);
                                int currentPage = instance.getCurrentPage();
                                imageview.setCounter((currentPage - 1)
                                        * instance.MAX_IMAGE_PER_PAGE
                                        + imageCounter++);
                                if (i < allPhotographsOfFolder.size()) {
                                    try {
                                        imageview
                                                .setImage(allPhotographsOfFolder
                                                        .get(i));
                                    } catch (Exception e) {
                                        LOGGER.error(e);
                                    }
                                } else {
                                    imageview.hide();
                                }
                            }
                            if (length < allPhotographsOfFolder.size()) {
                                for (int i = imageCounter; i < allPhotographsOfFolder
                                        .size(); i++) {
                                    Photograph p = allPhotographsOfFolder
                                            .get(i);
                                    try {
                                        addImageToPanel(p);
                                    } catch (IOException e) {
                                        LOGGER.error("error", e);
                                    }
                                }
                            }
                        }
                        if (length == 0) {
                            for (Photograph p : allPhotographsOfFolder) {
                                try {
                                    imageCounter++;
                                    addImageToPanel(p);
                                } catch (Exception e) {
                                    LOGGER.error("error", e);
                                }
                            }
                        }
                        long end = System.nanoTime();
                        LOGGER.info("ThumbnailPanel.ThumbnailPanel().new EventHandler() {...}.ThumbnailPanel() finished in "
                                + (end - start) / 1000000 + " ms");
                    }
                });
        EventManager.getInstance().listenToEventType(EventType.IMAGE_IMPORTED,
                new EventHandler() {
                    @Override
                    public void handle(ApplicationEvent event) {
                        List<Photograph> allPhotographsOfFolder = ModelLocator
                                .getInstance().getAllShowingImage();
                        try {
                            int lastImageCounter = allPhotographsOfFolder
                                    .size() - 1;
                            if (getLength() < allPhotographsOfFolder.size()) {
                                addImageToPanel(allPhotographsOfFolder
                                        .get(lastImageCounter), instance
                                        .getTotalImageBeingImported());
                            } else {
                                if (allPhotographsOfFolder.size() < instance.MAX_IMAGE_PER_PAGE) {
                                    ThumbnailView component = (ThumbnailView) get(lastImageCounter);
                                    component.setImage(allPhotographsOfFolder
                                            .get(lastImageCounter));
                                    component
                                            .setCounter(
                                                    imageCounter++,
                                                    instance.getTotalImageBeingImported());
                                } else {
                                    LOGGER.info("IMPORTING"
                                            + allPhotographsOfFolder.get(
                                                    lastImageCounter)
                                                    .getFileName()
                                            + " but not adding to workspce");
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    void updateImageView(ThumbnailView imageView, Photograph photograph)
            throws Exception {
        imageView.setCounter(imageCounter++);
        imageView.setImage(photograph);
    }

    void addImageToPanel(Photograph image) throws IOException {
        Border border = new Border();
        try {
            border.setStyles("{padding:5}");
        } catch (SerializationException e) {
            e.printStackTrace();
        }
        try {
            add(getImageView(image));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void addImageToPanel(Photograph image, int counter) throws IOException {
        Border border = new Border();
        try {
            border.setStyles("{padding:5}");
        } catch (SerializationException e) {
            e.printStackTrace();
        }
        try {
            ThumbnailView imageView = (ThumbnailView) getImageView(image);
            imageView.setCounter(imageCounter++, counter);
            add(imageView);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Container getImageView(final Photograph image) throws Exception {
        BXMLSerializer bxmlSerializer = new BXMLSerializer();
        final ThumbnailView component = (ThumbnailView) bxmlSerializer
                .readObject(MainWindow.class, "tnail.xml");
        component.initialize(bxmlSerializer.getNamespace(), null, null);
        component.setImage(image);
        return component;
    }

    @Override
    public void initialize(Map<String, Object> namespace, URL arg1,
            Resources arg2) {
    }
}
